package com.retail.order.client.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.retail.core.entity.enums.DelFlagEnum;
import com.retail.core.entity.enums.StatusFlagEnum;
import com.retail.core.entity.result.Result;
import com.retail.msg.entity.request.RetailMsgRequest;
import com.retail.msg.enums.MsgTypeEnums;
import com.retail.msg.service.RetailMsgService;
import com.retail.order.client.RetailSettleOrderClient;
import com.retail.order.entity.request.RetailSettleOrderRequest;
import com.retail.order.entity.vo.RetailSettleOrderVo;
import com.retail.order.enums.OrderStatusEnums;
import com.retail.order.service.RetailSettleOrderService;
import com.retail.shop.entity.request.RetailShopRequest;
import com.retail.shop.entity.vo.RetailShopVo;
import com.retail.shop.enums.ShopSourceEnums;
import com.retail.shop.service.RetailShopService;
import com.retail.system.entity.vo.AdminVo;
import com.retail.system.entity.vo.TableTreeVo;
import com.retail.system.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class RetailSettleOrderClientImpl implements RetailSettleOrderClient {

    @Autowired
    private RetailSettleOrderService retailSettleOrderService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private RetailShopService retailShopService;

    @Autowired
    private RetailMsgService retailMsgService;

    @Override
    public Result<List<TableTreeVo>> adminOrderTableTree(Long adminId) {
//        List<RetailSettleOrderVo> ret = new ArrayList<>();
//        // 商户信息
//        List<RetailSettleOrderVo> retailOrderList = retailSettleOrderService.findSuccessOwnerOrderByAdminId(adminId + "");
//        ret.addAll(retailOrderList);
//        List<AdminVo> childs = adminService.childAdminByParentId(adminId);
//        childs.forEach(c -> {
            List<RetailSettleOrderVo> retailOrderList2 = retailSettleOrderService.findSuccessOwnerOrderByAdminIdAndId(adminId + "");
//            ret.addAll(retailOrderList2);
//        });

        return Result.success(retailOrderList2);
    }

    @Override
    public Result<Integer> multiFile(Long fileId) {
        return Result.success("导入文件");
    }

    private void convertXls(String filePath) {
        File file = new File(filePath);
        ExcelReader excelReader = ExcelUtil.getReader(file, 0);
        List<List<Object>> dataList = excelReader.read(3);
        List<RetailSettleOrderRequest> orderRets = getOrders(dataList);
        List<RetailShopRequest> shopRets = orderPickUpShop(orderRets);

        for (RetailSettleOrderRequest order : orderRets) {
            String orderId = order.getOrderId();
            RetailSettleOrderVo retailSettleOrderVo = retailSettleOrderService.getModelByOrderIdAndSource(orderId, ShopSourceEnums.DY_TYPE.getValue());
            if (ObjectUtil.isNotEmpty(retailSettleOrderVo)) {
                order.setId(retailSettleOrderVo.getId());
                retailSettleOrderService.update(order);
            } else {
                retailSettleOrderService.save(order);
            }

            if (ObjectUtil.isEmpty(retailSettleOrderVo) ||
                    ObjectUtil.notEqual(order.orderHashMd5(), retailSettleOrderVo.orderHashMd5())) {
                insertOrderMsg(order);
            }
        }

        shopRets.forEach(shop -> {
            String poiId = shop.getPoiId();
            RetailShopVo retailShopVo = retailShopService.getmodelByPoiIdAndSource(poiId, shop.getShopSource());
            if (ObjectUtil.isNotEmpty(retailShopVo)) {
                shop.setId(retailShopVo.getId());
                retailShopService.update(shop);
            } else {
                retailShopService.save(shop);
            }
        });

        System.out.println(excelReader);
    }

    private void insertOrderMsg(RetailSettleOrderRequest shop) {
        // 插入记录数据
        RetailMsgRequest request = new RetailMsgRequest();
        request.setMsgType(MsgTypeEnums.ORDER_MSG.getValue());
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("订单来源：抖音订单," +
                "订单编号：" + shop.getOrderId() + ",");
        stringBuffer.append("订单金额：" + shop.getReceiptAmount() + ",");
        stringBuffer.append("订单时间：" + shop.getPayTime() + ",");
        stringBuffer.append("当前状态为：" + OrderStatusEnums.getStatusValues(shop.getOrderStatus()));
        request.setMsgContent(stringBuffer.toString());

        AdminVo adminVo = adminService.getModelByPoiId(shop.getPoiId());
        if (ObjectUtil.isNotEmpty(adminVo)) {
            request.setMsgUser(adminVo.getId() + "");
        }
        request.setDelFlag(DelFlagEnum.NO.getValue());
        request.setStatusFlag(StatusFlagEnum.USE.getValue());
        request.setCreateUser(1L);
        request.setRemark("订单推送");
        Long id = retailMsgService.save(request);
        retailMsgService.delayMsg(id);
    }


    public static List<RetailShopRequest> orderPickUpShop(List<RetailSettleOrderRequest> orderRets) {
        List<RetailShopRequest> shopRets = new ArrayList<RetailShopRequest>();
        List<String> shopIds = new ArrayList<>();
        orderRets.forEach(order -> {
            RetailShopRequest request = new RetailShopRequest();
            request.setShopSource(order.getOrderSource());
            request.setPoiId(order.getPoiId());
            request.setPoiName(order.getPoiName());
            request.setAddress("");
            request.setLatitude("");
            request.setLongitude("");
            request.setAccountId(order.getAccountId());
            request.setAccountName(order.getAccountName());
            request.setDelFlag(DelFlagEnum.NO.getValue());
            request.setStatusFlag(StatusFlagEnum.USE.getValue());
            request.setCreateUser(0L);
            request.setRemark(order.getRemark());

            if (!ObjectUtil.contains(shopIds, request.getPoiId())) {
                shopRets.add(request);
                shopIds.add(request.getPoiId());
            }
        });

        return shopRets;
    }

    public static List<RetailSettleOrderRequest> getOrders(List<List<Object>> dataList) {
        List<RetailSettleOrderRequest> ret = new ArrayList<>();
        for (List<Object> l : dataList) {
            RetailSettleOrderRequest retailOrderRequest = new RetailSettleOrderRequest();
//            retailOrderRequest.setSearchOwnerMsg();
//            retailOrderRequest.setSearchUserIds();
//            retailOrderRequest.setSearchAdminIds();
            retailOrderRequest.setShopNumber(l.get(3) + "");
            String orderTypeName = l.get(2) + "";
            // 订单类型，21-团购，31-预售，41、90-外卖，51、70-次卡，60-券交易
            Integer orderType = ObjectUtil.equal(orderTypeName, "团购") ? 21 :
                    ObjectUtil.equal(orderTypeName, "预售") ? 31 :
                            ObjectUtil.equal(orderTypeName, "外卖") ? 41 :
                                    ObjectUtil.equal(orderTypeName, "次卡") ? 51 :
                                            ObjectUtil.equal(orderTypeName, "券交易") ? 60 : 0;
            retailOrderRequest.setOrderType(orderType);

            retailOrderRequest.setOrderSource(ShopSourceEnums.MT_TYPE.getValue());
            retailOrderRequest.setOrderId(l.get(3) + "");
            retailOrderRequest.setOrderStatus(1);
            retailOrderRequest.setAccountId(l.get(9) + "");
            retailOrderRequest.setAccountName(l.get(10) + "");
            retailOrderRequest.setPoiId(l.get(9) + "");
            retailOrderRequest.setPoiName(l.get(10) + "");
//            retailOrderRequest.setNum();
            retailOrderRequest.setProductId(l.get(7) + "");
            retailOrderRequest.setProductName(l.get(8) + "");
            retailOrderRequest.setOriginalAmount(new BigDecimal(l.get(12) + ""));
            retailOrderRequest.setReceiptAmount(new BigDecimal(l.get(19) + ""));
            retailOrderRequest.setPaymentDiscount(new BigDecimal(l.get(19) + ""));
            retailOrderRequest.setPayAmount(new BigDecimal(l.get(19) + ""));
            retailOrderRequest.setPayTime((DateUtil.parseDate(l.get(21) + "").getTime() / 1000) + "");
            retailOrderRequest.setDelFlag(DelFlagEnum.NO.getValue());
            retailOrderRequest.setStatusFlag(StatusFlagEnum.USE.getValue());
            retailOrderRequest.setCreateUser(3L);
//            retailOrderRequest.setCreateTime();
//            retailOrderRequest.setUpdateTime();
            retailOrderRequest.setRemark("xls 美团导入");
            ret.add(retailOrderRequest);
        }

        return ret;
    }

    public void main(String[] args) {
        convertXls("C:\\Users\\Administrator\\Desktop\\nginx-1.23.0\\44889063_团购收支明细_20240601~20240630_17204033785791726357773275.xlsx");
    }
}
